<script setup lang="ts">

import {Classify, Result} from "~/api/responseResult";
import {changeClassify, classifyList, classifyListByClassify, saveClassify} from "~/api/warehouse";
import {ElMessage, ElMessageBox} from "element-plus";

const props = defineProps<{
  refresh: Function,
  getClassifyList: Function
}>()

const dialogVisible = ref(false)

const state: { tableClassifyPid: string, classifyListData: Array<Classify>, pid: string } = reactive({
  tableClassifyPid: '',
  classifyListData: [],
  pid: ''
})

const handleClose = () => {
  dialogVisible.value = false
}

const submit = async () => {
  const res: Result<any> = await changeClassify({tableClassifyPid: state.tableClassifyPid, pid: state.pid})
  if (res.success) {
    handleClose()
    props.refresh()
    props.getClassifyList()
  }
}

const getClassifyListData = async (tableClassifyPid: string) => {
  const res: Result<Array<Classify>> = await classifyListByClassify({tableClassifyPid: tableClassifyPid});
  if (res.success) {
    state.classifyListData = res.data
  }
}

const open = (tableClassifyPid: string, pid: string) => {
  dialogVisible.value = true
  state.tableClassifyPid = tableClassifyPid
  getClassifyListData(tableClassifyPid)
  state.pid = pid
  // 查询分类下的企业的分类

}

const createCategory = () => {
  ElMessageBox.prompt('请输入分类名称', '保存分类', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
      .then(async ({value}) => {
        const json: any = {}
        json.classifyName = value
        const res: Result<any> = await saveClassify(json)
        if (res.success) {
          ElMessage({
            type: 'success',
            message: `保存成功`,
          })
          await getClassifyList()
        }
      })
      .catch((e) => {
        console.log("失败")
      })
}

const getClassifyList = async () => {
  const res: Result<Array<Classify>> = await classifyList()
  if (res.success) {
    state.classifyListData = res.data
  }
}
defineExpose({
  submit,
  open,
  createCategory
})
</script>

<template>
  <el-dialog
      v-model="dialogVisible"
      title="移动表格"
      width="30%"
      :before-close="handleClose"
  >
    <el-select v-model="state.tableClassifyPid" placeholder="移动至">
      <el-option
          v-for="item in state.classifyListData"
          :key="item.pid"
          :label="item.classifyName"
          :value="item.pid"
      >
      </el-option>
    </el-select>
    <el-button style="margin-left: 5px;width: 35%" @click="createCategory">创建新分类</el-button>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
